#!/usr/bin/env Rscript
# -*- coding: utf-8 -*-
#
# @File    : species_accumulation_plot.R
# @Description : 绘制样本累积物种数图（带百分比辅助线和标注）

suppressPackageStartupMessages({
  library(optparse)
  library(tidyverse)
  library(ggplot2)
})

# --------------------------
# 参数解析
# --------------------------
option_list <- list(
  make_option(c("-i", "--input"), type="character", help="输入文件，包含 SampleN 和 SpeciesN 两列"),
  make_option(c("--pdf"), type="character", help="输出 PDF 文件路径"),
  make_option(c("--png"), type="character", help="输出 PNG 文件路径"),
  make_option(c("--width"), type="numeric", default=24, help="图宽度 (inch)"),
  make_option(c("--height"), type="numeric", default=8, help="图高度 (inch)"),
  make_option(c("--dpi"), type="numeric", default=300, help="PNG 分辨率")
)

opt_parser <- OptionParser(option_list=option_list)
opt <- parse_args(opt_parser)

# --------------------------
# 读取数据
# --------------------------
df <- read.table(opt$input, sep="\t", header=TRUE, check.names=FALSE)

# --------------------------
# 辅助线与标注计算
# --------------------------
total_samples <- max(df$SampleN, na.rm = TRUE)
percent_positions <- seq(0.1, 1, by = 0.1) * total_samples

annot_df <- data.frame(
  x = percent_positions,
  label = paste0(seq(10, 100, by = 10), "%"),
  SpeciesN = sapply(percent_positions, function(xpos) {
    idx <- which.min(abs(df$SampleN - xpos))
    df$SpeciesN[idx]
  })
)

# --------------------------
# 绘图
# --------------------------
p <- ggplot(data = df, aes(x = SampleN, y = SpeciesN)) +
  geom_col(color = "black", fill = "lightblue") +
  geom_line(color = "red", linewidth = 1) +
  geom_vline(xintercept = percent_positions, linetype = "dashed", color = "green") +
  geom_text(
    data = annot_df,
    aes(x = x, y = SpeciesN + 50, label = paste0(label, "\n(", SpeciesN, ")")),
    color = "black",
    size = 5,
    angle = 0,
    vjust = 0
  ) +
  scale_x_continuous(
    breaks = seq(min(df$SampleN, na.rm = TRUE),
                 max(df$SampleN, na.rm = TRUE),
                 by = 5)
  ) +
  scale_y_continuous(
    breaks = seq(min(df$SpeciesN, na.rm = TRUE),
                 max(df$SpeciesN, na.rm = TRUE),
                 by = 200)
  ) +
  theme_bw() +
  labs(
    x = "Sample Number",
    y = "Microbe Number",
    title = "Micorbe Accumulation by Sample Percentage"
  ) +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.text = element_text(size = 14),
    axis.title = element_text(size = 18)
  )


# --------------------------
# 输出图像
# --------------------------
ggsave(opt$pdf, plot=p, width=opt$width, height=opt$height)
ggsave(opt$png, plot=p, width=opt$width, height=opt$height, dpi=opt$dpi)

message("✅ 输出完成：")
message("PDF 文件: ", opt$pdf)
message("PNG 文件: ", opt$png)
